package com.monkey.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.monkey.dao.pojo.SysUser;
import com.monkey.service.LoginService;
import com.monkey.utils.UserThreadLocal;
import com.monkey.vo.ErrorCode;
import com.monkey.vo.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author：monkey-L
 * @description: .
 * @date: 19:57 2021/10/5
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
         *功能描述:
         * @author monkey-L
         * 1.需要判断请求的接口路径， 是否为handlerMethod(Controller里面的方法)
         * 2.判断token是否为空，如果为空，则未登录，拦截他
         * 3.如果token不为空，登录验证 loginService checkToken
         * 4.如果认证成功，放行即可
         * @return
         */
        if (!(handler instanceof HandlerMethod)) {
            //handler 可能是RequestResourceHandler springboot 程序访问静态资源
            //默认去classpath下的static目录去查询
            return true;
        }
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            System.out.println("=====================");
            System.out.println(token);
        } else {
            System.out.println("=====================");
            System.out.println(token);
        }
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (StringUtils.isBlank(token)) {
            Results fail = Results.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(fail));
            return false;
        }
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            Results fail = Results.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(fail));
            return false;
        }
        //此处证明已经通过验证，放行
        //我们希望在controller中直接获取用户的信息
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除ThreadLocal中用完的信息，会有内存泄漏
        UserThreadLocal.remove();
    }
}
